package com.richinfo.ajax.server.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

/**
 * Created by WangXJ
 * 2019-06-27 14:41
 */
public class CrosFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		// 获取请求头的Origin
		String origin = req.getHeader("Origin");
		if (!StringUtils.isEmpty(origin)) {
			// 带cookie的请求，Origin必须是全匹配(具体的url)，不能是 *
			res.addHeader("Access-Control-Allow-Origin", origin);
		}
		// 简单请求
		res.addHeader("Access-Control-Allow-Methods", "*");
		
		// 非简单请求的设置
		// 支持所有自定义头
		String headers = req.getHeader("Access-Control-Request-Headers");
		if (!StringUtils.isEmpty(headers)) {
			res.addHeader("Access-Control-Allow-Headers", headers);
		}
//		res.addHeader("Access-Control-Max-Age", "3600");// 让浏览器缓存信息的时长，单位秒
		
		// 带cookie的跨域
		res.addHeader("Access-Control-Allow-Credentials", "true");
		
		chain.doFilter(request, response);
	}

}
